﻿using RLRT.Common;
using RLRT.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;

namespace RLRT.Web
{
    public partial class Receiving : LocalPage
    {
        #region 属性

        /// <summary>
        /// 页面类别 1一般 2外包
        /// </summary>
        private int CurrentType
        {
            get
            {
                object tempObject = ViewState["CurrentType"];
                return (tempObject != null) ? (int)tempObject : 0;
            }
            set
            {
                ViewState["CurrentType"] = value;
            }
        }

        #endregion

        private static readonly string fac = "RL";

        /// <summary>
        /// 页面加载
        /// </summary>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                #region 验证权限

                #endregion

                #region 获取参数

                string type = Request.QueryString["PageType"];
                if (type != null && type.Trim().Length != 0)
                {
                    this.CurrentType = Util.ToInt(type);
                }

                #endregion

                //初始化
                this.Initialize();
            }

            #region 页面标题

            PageTitle.Text = this.CurrentType == 1 ? "一般收货" : "外包收货";

            this.Title = PageTitle.Text;

            #endregion

            #region 页面要素


            #endregion
        }

        #region 初始化

        /// <summary>
        /// 初始化
        /// </summary>
        private void Initialize()
        {
            #region 页面内容

            using (RTProvider rtProvider = new RTProvider())
            {
                var whs = rtProvider.GetWarehouseList();
                LocalGlobal.BindListItems(WhCode, whs.DefaultView, "wmdes", "wmwhs", true);

                var ornos = rtProvider.GetOrNoCboList(this.CurrentType);
                LocalGlobal.BindListItems(ORDNO, ornos.DefaultView, "prlsord", "prlsord", true);
            }

            this.ORDNO.SelectedIndex = -1;
            this.WhCode.SelectedIndex = -1;
            this.VenNo.Text = string.Empty;
            this.VenName.Text = string.Empty;
            //this.Curr.Text = string.Empty;
            this.ShipNo.Text = string.Empty;
            this.RTNo.Text = string.Empty;
            this.chkPrint.Checked = false;

            #endregion

            //绑定列表
            //this.BindList();
        }

        #endregion

        #region 绑定数据

        /// <summary>
        /// 绑定列表
        /// </summary>
        private void BindList()
        {
            using (RTProvider rtProvider = new RTProvider())
            {
                if (ORDNO.SelectedValue.Trim().Length > 0)
                {
                    DataTable table = rtProvider.GetPRList(this.CurrentType, ORDNO.SelectedValue.Trim(), VenNo.Text.Trim());
                    List.DataSource = table;
                    List.DataBind();
                }
                else
                {
                    List.DataSource = null;
                    List.DataBind();
                }

                ViewState["ViewDT"] = this.CreateTable();
                BindTempData();
            }
        }

        /// <summary>
        /// 行绑定
        /// </summary>
        protected void List_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            switch (e.Row.RowType)
            {
                //数据行
                case DataControlRowType.DataRow:
                    #region 数据绑定

                    ////数据
                    //string rowStatus = ((DataRowView)e.Row.DataItem)["Status"].ToString().Trim();

                    ////控件
                    //HtmlInputCheckBox rowCheckControl = (HtmlInputCheckBox)e.Row.FindControl("RowCheck");

                    ////指派
                    //rowCheckControl.Disabled = (rowStatus == "S");

                    #endregion
                    break;

                case DataControlRowType.EmptyDataRow:
                case DataControlRowType.Header:
                case DataControlRowType.Separator:
                case DataControlRowType.Pager:
                case DataControlRowType.Footer:
                default:
                    break;
            }
        }

        /// <summary>
        /// 行绑定
        /// </summary>
        protected void RTList_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            switch (e.Row.RowType)
            {
                //数据行
                case DataControlRowType.DataRow:
                    #region 数据绑定

                    //是否勾选
                    string ischeck = ((DataRowView)e.Row.DataItem)["ischeck"].ToString().Trim();

                    //控件
                    HtmlInputCheckBox rowCheckControl = (HtmlInputCheckBox)e.Row.FindControl("RowCheck");

                    //指派
                    rowCheckControl.Checked = (ischeck == "Y");

                    #endregion
                    break;

                case DataControlRowType.EmptyDataRow:
                case DataControlRowType.Header:
                case DataControlRowType.Separator:
                case DataControlRowType.Pager:
                case DataControlRowType.Footer:
                default:
                    break;
            }
        }

        #endregion

        #region 操作

        /// <summary>
        /// 查询
        /// </summary>
        protected void OKButton_Click(object sender, EventArgs e)
        {
            this.BindList();
        }

        /// <summary>
        /// 取消
        /// </summary>
        protected void CancelButton_Click(object sender, EventArgs e)
        {
            this.Initialize();
            this.BindList();
        }

        /// <summary>
        /// 新增RTList临时行
        /// </summary>
        protected void CreateButton_Click(object sender, EventArgs e)
        {
            var table = ViewState["ViewDT"] as DataTable;

            foreach (GridViewRow row in List.Rows)
            {
                HtmlInputCheckBox rowCheckControl = (HtmlInputCheckBox)row.FindControl("RowCheck");
                if (rowCheckControl.Checked)
                {
                    var newRow = table.NewRow();
                    newRow["ischeck"] = "Y";
                    newRow["prlno"] = row.Cells[1].Text.Trim();
                    newRow["prlseq"] = row.Cells[2].Text.Trim();
                    newRow["prlsord"] = row.Cells[3].Text.Trim();
                    newRow["prltno"] = row.Cells[4].Text.Trim();
                    newRow["bomnam"] = row.Cells[5].Text.Trim();
                    newRow["bommat"] = row.Cells[6].Text.Trim();
                    newRow["prlstation"] = row.Cells[7].Text.Trim();
                    newRow["prlum"] = row.Cells[8].Text.Trim();
                    newRow["prlqty"] = row.Cells[9].Text.Trim();
                    newRow["openqty"] = row.Cells[10].Text.Trim();
                    newRow["perWeight"] = "0";
                    newRow["sumWeight"] = "0";

                    //保存临时数据后重新绑定gridview
                    table.Rows.Add(newRow);
                }
            }

            ViewState["ViewDT"] = table;
            BindTempData();
        }

        /// <summary>
        /// 删除RTList临时行
        /// </summary>
        protected void DeleteButton_Click(object sender, EventArgs e)
        {
            DataTable table = ViewState["ViewDT"] as DataTable;

            bool deleted = false;
            foreach (GridViewRow row in RTList.Rows)
            {
                HtmlInputCheckBox rowCheckControl = (HtmlInputCheckBox)row.FindControl("RowCheck");
                if (rowCheckControl.Checked)
                {
                    var prlno = row.Cells[1].Text.Trim(); //订单号码
                    var prlseq = row.Cells[2].Text.Trim(); //序号
                    var prltno = row.Cells[4].Text.Trim(); //工件号
                    foreach (DataRow dr in table.Rows)
                    {
                        if (dr["prlno"].ToString().Trim() == prlno && dr["prltno"].ToString().Trim() == prltno && dr["prlseq"].ToString().Trim() == prlseq)
                        {
                            table.Rows.Remove(dr);
                            break;
                        }
                    }
                    //有项被删除
                    deleted = true;
                }
            }
            if (deleted)
            {
                ViewState["ViewDT"] = table;
                BindTempData();
            }
            else
            {
                this.ShowInfoMessage(this.GetGlobalResourceString("NotSelectMessage"));
            }
        }

        /// <summary>
        /// 保存
        /// </summary>
        protected void SaveButton_Click(object sender, EventArgs e)
        {
            SqlConnection con = LocalGlobal.DbConnect();
            con.Open();
            SqlTransaction tran = con.BeginTransaction();//使用事务
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = con;
            cmd.Transaction = tran;

            var dateModel = LocalGlobal.GetDateModel();

            using (RTProvider rtProvider = new RTProvider())
            {
                try
                {
                    string whCode = WhCode.SelectedValue.Trim();
                    string rtNo = LocalGlobal.NewRTNo(fac, whCode);
                    cmd.CommandText = rtProvider.UpdateNewRTNoSql(fac, whCode, rtNo);
                    cmd.ExecuteNonQuery();

                    #region Insert

                    bool flag = false;
                    int seq = 0;
                    foreach (GridViewRow row in RTList.Rows)
                    {
                        HtmlInputCheckBox rowCheckControl = (HtmlInputCheckBox)row.FindControl("RowCheck");
                        if (rowCheckControl.Checked)
                        {
                            string openqty = row.Cells[10].Text.Trim();  //待交货数量
                            string rtQty = ((TextBox)row.FindControl("rtqty")).Text.Trim(); //收货数量

                            #region 检测

                            if (Util.ToDecimal(rtQty) <= 0)
                            {
                                tran.Rollback();
                                this.ShowWarningMessage("请输入本次收货数量！");
                                return;
                            }
                            if (Util.ToDecimal(rtQty) > Util.ToDecimal(openqty))
                            {
                                tran.Rollback();
                                this.ShowWarningMessage("本次收货数量须小于待交货数量！");
                                return;
                            }

                            #endregion

                            seq++;
                            string perWeight = ((TextBox)row.FindControl("perWeight")).Text.Trim();
                            string sumWeight = ((TextBox)row.FindControl("sumWeight")).Text.Trim();
                            string remark = ((TextBox)row.FindControl("remark")).Text.Trim();
                            string odNo = row.Cells[1].Text.Trim();  //订单号码
                            string prlseq = row.Cells[2].Text.Trim();  //序号
                            string orNo = row.Cells[3].Text.Trim();  //工令号
                            string prltno = row.Cells[4].Text.Trim();  //工件号
                            string prlstation = row.Cells[7].Text.Trim();  //工站

                            string rtType, rtTypeDesc;
                            if (this.CurrentType == 1) //一般
                            {
                                rtType = orNo.Length == 0 ? "02" : "00";
                                rtTypeDesc = "一般收货";
                                prlstation = " ";
                            }
                            else  //外包
                            {
                                rtType = "01";
                                rtTypeDesc = "外包收货";
                                perWeight = "0";
                                sumWeight = "0";
                            }

                            var vendor = rtProvider.GetVendor(VenNo.Text.Trim());
                            string tax = vendor == null ? string.Empty : vendor["avtax"].ToString().Trim();

                            cmd.CommandText = rtProvider.InsertRTRecordSql(rtNo, seq.ToString(), rtType, prltno, fac, whCode, perWeight, ShipNo.Text.Trim(), odNo, orNo, prlstation, VenNo.Text.Trim(), rtQty, "", tax, row.Cells[8].Text.Trim(), remark, LocalGlobal.CurrentUserID, dateModel.DateStr, dateModel.TimeStr, rtTypeDesc, prlseq, sumWeight, rtQty); //入库和收货合并，收货数量及入库数量
                            cmd.ExecuteNonQuery();

                            cmd.CommandText = rtProvider.UpdatePRQtySql(odNo, prlseq, rtQty);
                            cmd.ExecuteNonQuery();

                            //更新库存数量
                            var invTable = rtProvider.GetInventoryByItem(whCode, prltno);
                            if (invTable != null && invTable.Rows.Count > 0)
                            {
                                cmd.CommandText = rtProvider.UpdateInventorySql(whCode, prltno, rtQty);
                                cmd.ExecuteNonQuery();
                            }
                            else
                            {
                                string bomName = row.Cells[5].Text.Trim(); //rtProvider.GetBomName(orNo, odNo, prlseq);

                                cmd.CommandText = rtProvider.InsertInventorySql(whCode, prltno, "", "", bomName, rtQty, row.Cells[8].Text.Trim());
                                cmd.ExecuteNonQuery();
                            }

                            flag = true;
                        }
                    }

                    if (!flag)
                    {
                        this.ShowInfoMessage(this.GetGlobalResourceString("NotSelectMessage"));
                        tran.Rollback();
                        return;
                    }

                    #endregion

                    RTNo.Text = rtNo;
                }
                catch (Exception error)
                {
                    tran.Rollback();
                    this.ShowErrorMessage("保存失败。" + error.Message);
                    return;
                }

                tran.Commit();

                this.BindList();

                if (chkPrint.Checked)
                {
                    //打印
                    this.ClientScript.RegisterStartupScript(this.GetType(), "print", "Print();", true);
                }
            }
        }

        #endregion

        #region 创建表结构及绑定
        protected DataTable CreateTable()
        {
            //定义table结构   
            DataTable dt1 = new DataTable();
            //不设置 默认为System.String  
            dt1.Columns.Add("ischeck");
            dt1.Columns.Add("prlno");
            dt1.Columns.Add("prlseq");
            dt1.Columns.Add("prlsord");
            dt1.Columns.Add("prltno");
            dt1.Columns.Add("bomnam");
            dt1.Columns.Add("bommat");
            dt1.Columns.Add("prlstation");
            dt1.Columns.Add("prlum");
            dt1.Columns.Add("prlqty");
            dt1.Columns.Add("openqty");
            dt1.Columns.Add("rtqty");
            dt1.Columns.Add("perWeight");
            dt1.Columns.Add("sumWeight");
            dt1.Columns.Add("remark");
            //dt1.Rows.Add(dt1.NewRow());
            //ViewState["ViewDT"] = dt1;
            return dt1;
        }

        protected void BindTempData()
        {
            this.RTList.DataSource = ViewState["ViewDT"] as DataTable;
            this.RTList.DataBind();

            if (this.CurrentType == 1)
            {
                this.RTList.Columns[12].Visible = true;
                this.RTList.Columns[13].Visible = true;
            }
            else
            {
                this.RTList.Columns[12].Visible = false;
                this.RTList.Columns[13].Visible = false;
            }
        }

        #endregion
    }
}